<script setup>
import { ref, onMounted, nextTick } from "vue";
import { ElButton, ElCard, ElTag, ElEmpty, ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";

// 考核计划数据结构
const plans = ref([]);
const loading = ref(false);

// 获取考核计划列表
async function fetchPlans() {
  loading.value = true;
  try {
    const response = await axios.get("http://localhost:8080/emp/getAssessmentPlan", {
      headers: {
        token: localStorage.getItem("token"),
      },
      params: {
        employeeId: Number(localStorage.getItem("employeeId")),
      },
    });

    console.log(response);
    
    if (response.data.code === 200) {
      plans.value = response.data.data || [];
      if (plans.value.length === 0) {
        ElMessage.warning("暂无考核计划数据");
      } else {
        ElMessage.success("考核计划加载成功");
      }
    } else {
      ElMessage.error(response.data.msg || "获取考核计划失败");
    }
  } catch (error) {
    console.error("获取考核计划失败:", error);
    ElMessage.error("网络错误，请稍后重试");
  } finally {
    loading.value = false;
  }
}

// 格式化日期显示
function formatDate(dateString) {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleDateString("zh-CN");
}

// 获取状态文本
function getStatusText(status) {
  if (status == 1) return "进行中";
  if (status == 0) return "已完成";
  if (status == -1) return "待执行";
  return "未知";
}

// 获取状态类型
function getStatusType(status) {
  if (status == 1) return "primary";
  if (status == 0) return "success";
  if (status == -1) return "info";
  return "default";
}

// 合并进行中和已完成的考核计划弹窗
async function handleShowPlanDetail(plan) {
  try {
    const response = await axios.get("http://localhost:8080/emp/getAssessmentPlan/getAssessmentIndicator", {
      headers: {
        token: localStorage.getItem("token"),
      },
      params: {
        planId: plan.planId,
        empId: Number(localStorage.getItem("employeeId")),
      },
    });
    if (response.data.code === 200) {
      // 兼容后端返回结构：进行中有 result 字段，已完成直接是数组
      let indicators = response.data.data.indicators || response.data.data || [];
      let result = response.data.data.result || {};
      let indicatorHtml = "";
      if (Array.isArray(indicators) && indicators.length > 0) {
        indicatorHtml = `
          <table style="width:100%;border-collapse:collapse;margin-top:10px;">
            <thead>
              <tr>
                <th style="border:1px solid #eee;padding:4px;">指标编号</th>
                <th style="border:1px solid #eee;padding:4px;">名称</th>
                <th style="border:1px solid #eee;padding:4px;">类型</th>
                <th style="border:1px solid #eee;padding:4px;">评分标准</th>
                <th style="border:1px solid #eee;padding:4px;">权重</th>
                <th style="border:1px solid #eee;padding:4px;">分数</th>
                <th style="border:1px solid #eee;padding:4px;">评语</th>
              </tr>
            </thead>
            <tbody>
              ${indicators.map(ind => `
                <tr>
                  <td style="border:1px solid #eee;padding:4px;">${ind.indicatorId}</td>
                  <td style="border:1px solid #eee;padding:4px;">${ind.indicatorName}</td>
                  <td style="border:1px solid #eee;padding:4px;">${ind.indicatorType}</td>
                  <td style="border:1px solid #eee;padding:4px;">${ind.scoringStandard}</td>
                  <td style="border:1px solid #eee;padding:4px;">${ind.weight}</td>
                  <td style="border:1px solid #eee;padding:4px;">${ind.score ?? '-'}</td>
                  <td style="border:1px solid #eee;padding:4px;">${ind.comment ?? '-'}</td>
                </tr>
              `).join('')}
            </tbody>
          </table>
        `;
      } else {
        // 没有考核指标时，只显示简洁内容
        await ElMessageBox.alert(
          `<div class="text-left">
            <h3 class="text-lg font-bold mb-3">考核指标详情</h3>
            <p><strong>计划名称：</strong>${plan.planName}</p>
            <p><strong>考核得分：</strong>${result.score ?? '-'}</p>
            <p><strong>评价等级：</strong>${result.evaluationLevel ?? '-'}</p>
            <div style="margin-top:10px;">
              <strong>考核指标：</strong>
              <p>暂无考核指标</p>
            </div>
          </div>`,
          "考核指标",
          {
            dangerouslyUseHTMLString: true,
            confirmButtonText: "我知道了",
            type: "info",
            customClass: "large-message-box",
          }
        );
        return;
      }
      let actionBtnsHtml = `
        <button id="export-echart-btn" style="padding: 4px 12px; background: #409EFF; color: #fff; border: none; border-radius: 4px; cursor: pointer;">导出图片</button>
      `;
      if (result.status === 0) {
        actionBtnsHtml += `
          <button id="objection-btn" style="padding: 4px 12px; background: #f59e42; color: #fff; border: none; border-radius: 4px; cursor: pointer;">提交异议</button>
          <button id="confirm-btn" style="padding: 4px 12px; background: #67c23a; color: #fff; border: none; border-radius: 4px; cursor: pointer;">确认无误</button>
        `;
      }
      ElMessageBox.alert(
        `<div class="text-left">
          <h3 class="text-lg font-bold mb-3">考核指标详情</h3>
          <p><strong>计划名称：</strong>${plan.planName}</p>
          <p><strong>考核得分：</strong>${result.score ?? '-'}</p>
          <p><strong>评价等级：</strong>${result.evaluationLevel ?? '-'}</p>
          <div style="margin-top:10px;">
            <strong>考核指标：</strong>
            <div style="margin-bottom: 8px; display: flex; gap: 12px;">
              ${actionBtnsHtml}
            </div>
            <div id="echart-pie" style="width: 400px; height: 300px; margin: 32px 0;"></div>
            ${indicatorHtml}
          </div>
        </div>`,
        "考核指标",
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "我知道了",
          type: "info",
          customClass: "large-message-box",
        }
      );
      // 图表和按钮事件绑定
      const option = {
        title: { text: '权重分布', left: 'center' },
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            const score = indicators[params.dataIndex].score ?? '-';
            return `${params.name}<br/>权重: ${params.value}<br/>分数: ${score}`;
          }
        },
        series: [
          {
            name: '权重',
            type: 'pie',
            radius: '60%',
            label: {
              formatter: (params) => {
                const score = indicators[params.dataIndex].score ?? '-';
                return `${params.name}\n分数:${score}`;
              }
            },
            data: indicators.map(ind => ({
              value: Number(ind.weight),
              name: ind.indicatorName,
              score: ind.score
            }))
          }
        ]
      };
      const observer = new MutationObserver(() => {
        const chartDom = document.getElementById('echart-pie');
        if (chartDom && window.echarts) {
          observer.disconnect();
          const myChart = window.echarts.init(chartDom);
          myChart.setOption(option);
          myChart.resize();
          // 导出图片按钮
          const exportBtn = document.getElementById('export-echart-btn');
          if (exportBtn) {
            exportBtn.onclick = () => {
              const img = myChart.getDataURL({
                type: 'png',
                pixelRatio: 2,
                backgroundColor: '#fff'
              });
              const link = document.createElement('a');
              link.href = img;
              link.download = 'chart.png';
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
            };
          }
          // 只有进行中（result.status === 0）才有异议和确认按钮
          if (result.status === 0) {
            const objectionBtn = document.getElementById('objection-btn');
            if (objectionBtn) {
              objectionBtn.onclick = () => {
                ElMessageBox.prompt('请输入您的异议内容', '提交异议', {
                  confirmButtonText: '提交',
                  cancelButtonText: '取消',
                  inputType: 'textarea',
                  inputPlaceholder: '请填写您的异议...',
                  inputValidator: (value) => {
                    if (!value) return '异议内容不能为空';
                    return true;
                  }
                }).then(({ value }) => {
                  axios.post('http://localhost:8080/emp/saveDisputes', {
                    employeeId: Number(localStorage.getItem('employeeId')),
                    planId: plan.planId,
                    objectionContent: value
                  }, {
                    headers: {
                      'token': localStorage.getItem('token'),
                    }
                  }).then(res => {
                    if (res.data.code === 200) {
                      ElMessage.success('异议提交成功');
                    } else {
                      ElMessage.error(res.data.msg || '异议提交失败');
                    }
                  }).catch(() => {
                    ElMessage.error('网络错误，异议提交失败');
                  });
                }).catch(() => {});
              };
            }
            const confirmBtn = document.getElementById('confirm-btn');
            if (confirmBtn) {
              confirmBtn.onclick = () => {
                ElMessageBox.confirm('确认提交本次考核结果吗？', '确认无误', {
                  confirmButtonText: '确认',
                  cancelButtonText: '取消',
                  type: 'warning',
                }).then(() => {
                  axios.put('http://localhost:8080/emp/updataResultStatus', {
                    employeeId: Number(localStorage.getItem('employeeId')),
                    planId: plan.planId,
                    status: 1
                  }, {
                    headers: {
                      'token': localStorage.getItem('token'),
                    }
                  }).then(res => {
                    if (res.data.code === 200) {
                      ElMessage.success('确认成功');
                    } else {
                      ElMessage.error(res.data.msg || '确认失败');
                    }
                  }).catch(() => {
                    ElMessage.error('网络错误，确认失败');
                  });
                }).catch(() => {});
              };
            }
          }
        }
      });
      observer.observe(document.body, { childList: true, subtree: true });
    } else {
      ElMessage.error(response.data.msg || "获取考核指标失败");
    }
  } catch (error) {
    console.error("获取考核指标失败:", error);
    ElMessage.error("网络错误，请稍后重试");
  }
}

// 处理待执行的考核计划点击
async function handlePendingPlan(plan) {
  try {
    const response = await axios.get("http://127.0.0.1:8080/emp/getAssessmentIndicators", {
      headers: {
        'token': localStorage.getItem("token"),
      },
      params: {
        planId: plan.planId,
      },
    });

    if (response.data.code === 200) {
      const indicators = response.data.data;
      let indicatorHtml = "";
      if (Array.isArray(indicators) && indicators.length > 0) {
        indicatorHtml = `
          <table style="width:100%;border-collapse:collapse;margin-top:10px;">
            <thead>
              <tr>
                <th style="border:1px solid #eee;padding:4px;">指标编号</th>
                <th style="border:1px solid #eee;padding:4px;">名称</th>
                <th style="border:1px solid #eee;padding:4px;">类型</th>
                <th style="border:1px solid #eee;padding:4px;">评分标准</th>
                <th style="border:1px solid #eee;padding:4px;">权重</th>
              </tr>
            </thead>
            <tbody>
              ${indicators.map(ind => `
                <tr>
                  <td style="border:1px solid #eee;padding:4px;">${ind.indicatorId}</td>
                  <td style="border:1px solid #eee;padding:4px;">${ind.indicatorName}</td>
                  <td style="border:1px solid #eee;padding:4px;">${ind.indicatorType}</td>
                  <td style="border:1px solid #eee;padding:4px;">${ind.scoringStandard}</td>
                  <td style="border:1px solid #eee;padding:4px;">${ind.weight}</td>
                </tr>
              `).join('')}
            </tbody>
          </table>
        `;
      } else {
        indicatorHtml = `<p>暂无考核指标</p>`;
      }

      await ElMessageBox.alert(
        `<div class="text-left">
          <h3 class="text-lg font-bold mb-3">待执行考核详情</h3>
          <p><strong>计划名称：</strong>${plan.planName}</p>
          <p><strong>开始时间：</strong>${formatDate(plan.startDate)}</p>
          <p><strong>结束时间：</strong>${formatDate(plan.endDate)}</p>
          <div style="margin-top:10px;"><strong>考核指标：</strong>${indicatorHtml}</div>
        </div>`,
        "考核待执行",
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "准备就绪",
          type: "warning"
        }
      );
    } else {
      ElMessage.error(response.data.msg || "获取待执行考核详情失败");
    }
  } catch (error) {
    console.error("获取待执行考核详情失败:", error);
    ElMessage.error("网络错误，请稍后重试");
  }
}

// 处理考核计划点击
function handlePlanClick(plan) {
  const status = plan.status;
  if (status == 1 || status == 0) {
    // 进行中或已完成
    handleShowPlanDetail(plan);
  } else if (status == -1) {
    // 待执行
    handlePendingPlan(plan);
  } else {
    ElMessage.warning("未知状态，无法查看详情");
  }
}

// 初始化加载
onMounted(() => {
  fetchPlans();
});
</script>

<template>
  <div class="p-6">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-bold">考核计划列表</h2>
      <el-button type="primary" @click="fetchPlans" :loading="loading">
        <i class="fas fa-sync-alt mr-2"></i>刷新
      </el-button>
    </div>

    <!-- 有数据时展示列表 -->
    <div v-if="!loading && plans.length > 0" class="grid gap-4">
      <el-card
        v-for="plan in plans"
        :key="plan.planId"
        class="hover:shadow-lg transition-shadow cursor-pointer"
        @click="handlePlanClick(plan)"
      >
        <div class="flex justify-between items-start">
          <div class="flex-1">
            <div class="flex items-center gap-3 mb-2">
              <h3 class="text-lg font-semibold text-gray-800">{{ plan.planName }}</h3>
              <el-tag :type="getStatusType(plan.status)" size="small">
                {{ getStatusText(plan.status) }}
              </el-tag>
            </div>
            <div class="text-sm text-gray-600 space-y-1">
              <p>
                <i class="fas fa-calendar mr-2"></i>考核周期：{{ plan.assessmentCycle }}
              </p>
              <p>
                <i class="fas fa-building mr-2"></i>考核对象：{{ plan.departmentName }}
              </p>
              <p>
                <i class="fas fa-clock mr-2"></i>考核时间：{{
                  formatDate(plan.startDate)
                }}
                - {{ formatDate(plan.endDate) }}
              </p>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 空状态 -->
    <el-empty v-if="!loading && plans.length === 0" description="暂无考核计划" />
  </div>
</template>

<style scoped>
.el-card {
  border: 1px solid #e5e7eb;
}

.el-card:hover {
  border-color: #3b82f6;
}
</style>

<style>
.large-message-box {
  max-width: 900px !important;
  width: 80vw !important;
  min-width: 600px;
}
</style>
